package handler

import (
	"context"
	"mxshop_srvs/userop_srv/global"
	"mxshop_srvs/userop_srv/model"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"

	"mxshop_srvs/userop_srv/proto"
)

func (*UserOp) GetFavList(ctx context.Context, req *proto.UserFavRequest) (*proto.UserFavListResponse, error) {

	var userFavListResponse proto.UserFavListResponse
	var userFavList []model.UserFav
	var total int64

	if result := global.DB.Where("user=?", req.UserId).Count(&total); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	if result := global.DB.Where("user=?", req.UserId).Find(&userFavList); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有收藏数据")
	}
	userFavListResponse.Total = int32(total)
	for _, userFav := range userFavList {
		userFavResponse := proto.UserFavResponse{
			UserId:  userFav.User,
			GoodsId: userFav.Goods,
		}
		userFavListResponse.Data = append(userFavListResponse.Data, &userFavResponse)
	}
	return &userFavListResponse, nil
}
func (*UserOp) AddUserFav(ctx context.Context, req *proto.UserFavRequest) (*emptypb.Empty, error) {

	userFav := model.UserFav{
		User:  req.UserId,
		Goods: req.GoodsId,
	}
	if result := global.DB.Save(&userFav); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}

	return &emptypb.Empty{}, nil
}
func (*UserOp) DeleteUserFav(ctx context.Context, req *proto.UserFavRequest) (*emptypb.Empty, error) {

	if result := global.DB.Unscoped().Where("user=? and goods=?", req.UserId, req.GoodsId).Delete(&model.UserFav{}); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "收藏记录不存在")
	}

	return &emptypb.Empty{}, nil
}
func (*UserOp) GetUserFavDetail(context.Context, *proto.UserFavRequest) (*emptypb.Empty, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GetUserFavDetail not implemented")
}
